package com.lb.shopguide.ui.dialog;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.base.DialogBase;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.SimpleObserverOtherListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.tag.AdapterFlowTag;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.goods.GoodsDetailBean;
import com.lb.shopguide.entity.goods.GoodsInListBean;
import com.lb.shopguide.entity.goods.SkuBean;
import com.lb.shopguide.event.guide.SelectGoodsSkuEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.GuideMainActivity;
import com.lb.shopguide.ui.view.LbGoodsNumSelector;
import com.lb.shopguide.ui.view.flowlayout.Attribute;
import com.lb.shopguide.ui.view.flowlayout.FlowLayout;
import com.lb.shopguide.ui.view.flowlayout.TagAdapter;
import com.lb.shopguide.ui.view.flowlayout.TagFlowLayout;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.BizGoodsUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by kang on 2017/6/13.
 */

public class DialogSelectSku extends DialogBase implements View.OnClickListener {
    private ImageView ivGoods;
    private TextView tvGoods;
    private TextView tvPrice;
    private TextView tvSum;
    private TextView tvSure;
    private TagFlowLayout layoutSize;
    private TagFlowLayout layoutColor;
    private LbGoodsNumSelector selector;

    private GoodsInListBean mGoodsInListBean;
    private GoodsDetailBean mGoodsDetailBean;
    private ArrayList<SkuBean> mSkuList;

    private Attribute sizeAttr = new Attribute();
    private Attribute colorAttr = new Attribute();
    private List<String> mSizeList;//大小属性数据
    private List<String> mColorList;//颜色属性数据
    private List<String> mFailureSkuList;//无库存或不能选的所有组合sku
    private List<String> mAllSkuList;//所有的组合sku
    private int curColor;//临时记录的颜色
    private int curSize;//临时记录的大小

    private String colorStr;
    private String sizeStr;

    private AdapterFlowTag mSizeAdapter;
    private AdapterFlowTag mColorAdapter;

    public static DialogSelectSku getDialogSelectSku(GoodsInListBean bean) {
        DialogSelectSku dialogSelectSku = new DialogSelectSku();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.GOODS_BEAN_IN_LIST, bean);
        dialogSelectSku.setArguments(bundle);
        return dialogSelectSku;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mFragmentView = inflater.inflate(R.layout.dialog_select_sku, container, false);
        initData();
        initView(mFragmentView);

        setDialogPosition();
        return mFragmentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, R.style.dialog_bottom);
    }

    private void setDialogPosition() {
        Window window = getDialog().getWindow();
        window.setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL);
    }

    private void initData() {
        mSkuList = new ArrayList<>();
        mColorList = new ArrayList<>();
        mSizeList = new ArrayList<>();
        mFailureSkuList = new ArrayList<>();
        mAllSkuList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.GOODS_BEAN_IN_LIST)) {
            mGoodsInListBean = (GoodsInListBean) bundle.getSerializable(AppConstant.GOODS_BEAN_IN_LIST);
        }
        initRequest();
    }

    private void initView(View view) {
        ivGoods = view.findViewById(R.id.iv_product);
        tvGoods = view.findViewById(R.id.tv_product_name);
        tvPrice = view.findViewById(R.id.tv_price);
        tvSum = view.findViewById(R.id.tv_sum);
        tvSure = view.findViewById(R.id.tv_sure);
        selector = view.findViewById(R.id.selector);
        layoutColor = view.findViewById(R.id.layout_color);
        layoutSize = view.findViewById(R.id.layout_size);

        bindData();
        initListener();
    }


    private void initRequest() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    mGoodsDetailBean = (GoodsDetailBean) JsonUtil.getObject(response.getReturnContent(), GoodsDetailBean.class);
                    mSkuList = (ArrayList<SkuBean>) mGoodsDetailBean.getProductSkuList();
                    if (mSkuList.size() != 0) {
                        bindSku();
                    }
                }
            }
        };
        SimpleObserverOtherListener errorListener = new SimpleObserverOtherListener() {

            @Override
            public void onSessionOutOfDate() {
                ((GuideMainActivity) getActivity()).onSessionOutOfDate();
            }

            @Override
            public void onError(String error) {
                ToastUtils.showShort(error);
            }
        };
        ApiMethodGuide.getGoodsDetail(new SimpleLbObserver(listener, errorListener), mGoodsInListBean.getProductCode(), this, FragmentEvent.DESTROY_VIEW);
    }

    private void bindData() {
        tvGoods.setText(mGoodsInListBean.getProductName());
        tvPrice.setText("￥" + mGoodsInListBean.getPrice());
        ImageLoaderUtils.getGlideManager().asBitmap().load(mGoodsInListBean.getProductPicUrl()).apply(ImageLoaderUtils.getSGCommonGlideOption(4)).into(ivGoods);
    }

    private void bindSku() {
        List result = BizGoodsUtil.getSizeAndColorInDialog(mSkuList);
        //第一个是尺寸，第二个是颜色
        Map<String, String> mapSize = (Map<String, String>) result.get(0);
        Map<String, String> mapColor = (Map<String, String>) result.get(1);
        mSizeList.addAll(mapSize.keySet());
        sizeAttr.aliasName.addAll(mSizeList);
        mColorList.addAll(mapColor.keySet());
        colorAttr.aliasName.addAll(mColorList);

        for (SkuBean skuBean : mSkuList) {
            if (skuBean.isDefault()) {
                selector.setInitNumber("1");
                setSkuBean(skuBean);
            }
        }
        if (TextUtils.isEmpty(sizeStr) && TextUtils.isEmpty(colorStr)) {
            if (mSizeList.size() == 0 || mColorList.size() == 0) {

            } else {
                sizeStr = mSizeList.get(0);
                colorStr = mColorList.get(0);
            }
        }

        SkuBean curSkuBean = BizGoodsUtil.getCurSkuBean(sizeStr, colorStr, mSkuList);
        if (curSkuBean != null) {
            selectSku(curSkuBean);
        }

        for (Map.Entry<String, String> entryColor : mapColor.entrySet()) {
            for (Map.Entry<String, String> entrySize : mapSize.entrySet()) {
                mAllSkuList.add(entryColor.getKey() + ":" + entrySize.getKey());
                SkuBean skuBean = BizGoodsUtil.getCurSkuBean(entrySize.getKey(), entryColor.getKey(), mSkuList);
                if (skuBean == null) {
                    mFailureSkuList.add(entryColor.getKey() + ":" + entrySize.getKey());
                }
            }
        }
        mSizeAdapter = new AdapterFlowTag(GuideApplication.getAppContext(), sizeAttr);
        layoutSize.setAdapter(mSizeAdapter);
        for (int i = 0; i < mSizeList.size(); i++) {
            if (sizeStr.equals(mSizeList.get(i))) {
                mSizeAdapter.setSelectedList(i);
            }
        }
        mColorAdapter = new AdapterFlowTag(GuideApplication.getAppContext(), colorAttr);
        layoutColor.setAdapter(mColorAdapter);
        for (int i = 0; i < mColorList.size(); i++) {
            if (colorStr.equals(mColorList.get(i))) {
                mColorAdapter.setSelectedList(i);
            }
        }
        //颜色属性标签点击事件
        layoutColor.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            boolean unableFlag;

            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                unableFlag = false;
                //从Base类中拿到不可点击的属性名称进行比较
                List<String> st = colorAttr.getFailureAliasName();
                for (int i = 0; i < st.size(); i++) {
                    if (st.get(i).equals(mColorList.get(position))) {
                        unableFlag = true;
                    }
                }
                //如是不可点击就进接return 这样就形成了不可点击的假像，达到了我们的目的
                if (unableFlag) {
                    return true;
                }
                if (position == curColor) {
                    curColor = -1;
                    colorStr = "";
                    sizeAttr.failureAliasName.clear();
                    notifyColorAndSize();
                    return true;
                } else {
                    curColor = position;
                    colorStr = mColorList.get(position);
                }
                SkuBean skuBean = BizGoodsUtil.getCurSkuBean(sizeStr, colorStr, mSkuList);
                if (skuBean != null) {
                    selectSku(skuBean);
                }
                sizeAttr.failureAliasName.clear();
                for (int i = 0; i < mSizeList.size(); i++) {
                    String sku = colorStr + ":" + mSizeList.get(i);
                    for (int j = 0; j < mFailureSkuList.size(); j++) {
                        if (sku.equals(mFailureSkuList.get(j))) {
                            sizeAttr.failureAliasName.add(mSizeList.get(i));
                        }
                    }
                }
                notifyColorAndSize();
                return true;
            }
        });


        //大小属性标签点击事件
        layoutSize.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            boolean unableFlag;

            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                unableFlag = false;
                List<String> st = sizeAttr.getFailureAliasName();
                for (int i = 0; i < st.size(); i++) {
                    if (st.get(i).equals(mSizeList.get(position))) {
                        unableFlag = true;
                    }
                }
                if (unableFlag) {
                    return true;
                }
                if (position == curSize) {
                    curSize = -1;
                    sizeStr = "";
                    colorAttr.failureAliasName.clear();
                    notifyColorAndSize();
                    return true;
                } else {
                    curSize = position;
                    sizeStr = mSizeList.get(position);
                }
                SkuBean skuBean = BizGoodsUtil.getCurSkuBean(sizeStr, colorStr, mSkuList);
                if (skuBean != null) {
                    selectSku(skuBean);
                }
                colorAttr.failureAliasName.clear();
                for (int i = 0; i < mColorList.size(); i++) {
                    String sku = mColorList.get(i) + ":" + sizeStr;
                    for (int j = 0; j < mFailureSkuList.size(); j++) {
                        if (sku.equals(mFailureSkuList.get(j))) {
                            colorAttr.failureAliasName.add(mColorList.get(i));
                        }
                    }
                }
                notifyColorAndSize();
                return true;
            }
        });
    }

    private void initListener() {
        tvSure.setOnClickListener(this);
    }

    private void setSkuBean(SkuBean skuBean) {
        sizeStr = skuBean.getSize();
        colorStr = skuBean.getColor();
        mGoodsDetailBean.setSum(selector.getNumber());
        mGoodsDetailBean.setCurSkuBean(skuBean);
        EventBus.getDefault().post(new SelectGoodsSkuEvent(mGoodsDetailBean));
    }

    private void notifyColorAndSize() {
        notifyTagAdapterChange(mColorAdapter, curColor);
        notifyTagAdapterChange(mSizeAdapter, curSize);
    }

    public void notifyTagAdapterChange(TagAdapter Adapter, int CcInt) {
        Adapter.getPreCheckedList().clear();
        if (CcInt != -1) {
            Adapter.setSelectedList(CcInt);
        }
        Adapter.notifyDataChanged();
    }

    private void selectSku(SkuBean skuBean) {
        if (skuBean != null) {
            ImageLoaderUtils.getGlideManager().asBitmap().load(skuBean.getColorPicUrl())
                    .apply(ImageLoaderUtils.getSGCommonGlideOption(4)).into(ivGoods);
            tvSum.setText("库存 (" + skuBean.getStoreSum() + ")");
            tvPrice.setText("￥" + skuBean.getPrice());
        } else {
            ToastUtils.showShort("请检查该商品颜色尺码，重新选择");
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_sure:
                if (TextUtils.isEmpty(colorStr)) {
                    ToastUtils.showShort("请选择颜色");
                    return;
                }
                if (TextUtils.isEmpty(sizeStr)) {
                    ToastUtils.showShort("请选择尺寸");
                    return;
                }

                SkuBean skuBean = BizGoodsUtil.getCurSkuBean(sizeStr, colorStr, mSkuList);
                if (skuBean.getStoreSum() == 0) {
                    ToastUtils.showShort("该商品库存为0");
                    return;
                }
                mGoodsDetailBean.setSum(selector.getNumber());
                mGoodsDetailBean.setCurSkuBean(skuBean);
                EventBus.getDefault().post(new SelectGoodsSkuEvent(mGoodsDetailBean));
                DialogSelectSku.this.dismiss();
                break;
        }
    }
}
